"""
服务模块：系统配置信息
"""

import pickle

from app.common.redis import redis_cli
from app.setting import REDIS_EXPIRE_TIME
from app.dao.sysconfig import (SysConfigDao, SysConfig)


class SysConfigService(object):
    """
    系统配置信息service类
    """

    @classmethod
    def find_by_nid_and_type_and_status(cls, nid, type_, status):
        # 唯一键值
        key = "nid_" + str(nid) + "_type_" + str(type_) + "_status_" + str(status)

        # 先从缓存中获取，不存在再从数据库中获取
        item = redis_cli.get(key)
        if not item:
            obj = SysConfigDao.find_by_nid_and_type_and_status(nid=nid, type_=type_, status=status)
            if obj:
                obj_view = cls.__convert_to_view(obj)
                item = pickle.dumps(obj_view)
                redis_cli.set(key, item)
                redis_cli.expire(key, REDIS_EXPIRE_TIME)
        else:
            # 更新token的过期时间
            redis_cli.expire(key, REDIS_EXPIRE_TIME)

        item = pickle.loads(item) if item else None
        return item

    @classmethod
    def __convert_to_view(cls, item):
        """
        转化成视图对象
        :param item:
        :return:
        """

        result = None
        if isinstance(item, SysConfig):
            type_ = int(item.type)

            result = dict(id=int(item.id),
                          name=item.name,
                          nid=item.nid,
                          value=item.value,
                          type=type_,
                          )
        return result
